from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.conf import settings
import os
from .models import Bicycle, CollegeUser


@login_required
def refresh_qr_code(request, bike_id):
    """刷新单个自行车的二维码"""
    # 检查用户权限
    college_user = None
    is_super_admin = False
    
    try:
        college_user = CollegeUser.objects.get(user=request.user)
        is_super_admin = college_user.is_super_admin
    except CollegeUser.DoesNotExist:
        # 普通用户也可以刷新二维码
        pass
    
    # 获取自行车对象
    if is_super_admin:
        bike = get_object_or_404(Bicycle, id=bike_id)
    elif college_user and college_user.is_admin:
        bike = get_object_or_404(Bicycle, id=bike_id, college=college_user.college)
    else:
        # 普通用户可以刷新任意自行车的二维码
        bike = get_object_or_404(Bicycle, id=bike_id)
    
    try:
        # 删除旧的二维码文件
        if bike.qr_code:
            old_qr_path = os.path.join(settings.MEDIA_ROOT, str(bike.qr_code))
            if os.path.exists(old_qr_path):
                os.remove(old_qr_path)
        
        # 重新生成二维码
        bike.qr_code = None  # 清空当前二维码
        bike.save()  # 第一次保存清空二维码
        
        # 强制重新生成二维码
        print(f"正在为自行车 {bike.bike_number} 生成新二维码...")
        new_qr_code = bike.generate_qr_code()
        if new_qr_code:
            bike.qr_code = new_qr_code
            bike.save()  # 第二次保存生成新二维码
            print(f"自行车 {bike.bike_number} 二维码生成成功: {bike.qr_code}")
        else:
            raise Exception("二维码生成失败")
        
        messages.success(request, f'自行车 {bike.bike_number} 的二维码已刷新！')
    except Exception as e:
        messages.error(request, f'刷新二维码失败：{str(e)}')
    
    return redirect('bike:admin_bike_list')


@login_required
def batch_refresh_qr(request):
    """批量刷新二维码"""
    # 检查用户权限
    college_user = None
    is_super_admin = False
    
    try:
        college_user = CollegeUser.objects.get(user=request.user)
        is_super_admin = college_user.is_super_admin
    except CollegeUser.DoesNotExist:
        # 普通用户也可以批量刷新二维码
        pass
    
    if request.method == 'POST':
        bike_ids = request.POST.getlist('bike_ids')
        
        if not bike_ids:
            messages.error(request, '请选择要刷新二维码的自行车！')
            return redirect('bike:admin_bike_list')
        
        # 权限检查
        if is_super_admin:
            bikes = Bicycle.objects.filter(id__in=bike_ids)
        elif college_user and college_user.is_admin:
            bikes = Bicycle.objects.filter(id__in=bike_ids, college=college_user.college)
        else:
            # 普通用户可以刷新任意自行车的二维码
            bikes = Bicycle.objects.filter(id__in=bike_ids)
        
        if not bikes.exists():
            messages.error(request, '没有找到符合条件的自行车！')
            return redirect('bike:admin_bike_list')
        
        success_count = 0
        error_count = 0
        
        for bike in bikes:
            try:
                # 删除旧的二维码文件
                if bike.qr_code:
                    old_qr_path = os.path.join(settings.MEDIA_ROOT, str(bike.qr_code))
                    if os.path.exists(old_qr_path):
                        os.remove(old_qr_path)
                
                # 重新生成二维码
                bike.qr_code = None
                bike.save()  # 第一次保存清空二维码
                
                # 强制重新生成二维码
                new_qr_code = bike.generate_qr_code()
                if new_qr_code:
                    bike.qr_code = new_qr_code
                    bike.save()  # 第二次保存生成新二维码
                else:
                    raise Exception("二维码生成失败")
                
                success_count += 1
            except Exception as e:
                error_count += 1
                print(f"刷新自行车 {bike.bike_number} 二维码失败: {str(e)}")
        
        if success_count > 0:
            messages.success(request, f'成功刷新 {success_count} 辆自行车的二维码！')
        if error_count > 0:
            messages.warning(request, f'{error_count} 辆自行车的二维码刷新失败！')
    
    return redirect('bike:admin_bike_list')
